import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/constans/special_job_code.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/widget_extension.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/common/personnel_type.dart';
import 'package:enterprise_v6_app/app/data/entities/application/execute_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/role_personnel_entity.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';

/// 节点负责人选择
/// 业务需求变更,原本只需要选择返回节点负责人,后变更为选择节点负责人或作业人员并调用接口(节点负责人与作业人员分别流程逻辑和业务逻辑两套逻辑
/// 节点人员会进入到业务逻辑中,但返回时需要单独返回,设置进入节点数据中)
///[callback]点击回调
///[rolePersonnelList]初始的数据
///[nodeType]节点类型
///[ticketReceiptId]作业票id
class CustomResponsiblePerson extends StatefulWidget {
  const CustomResponsiblePerson({
    required this.callback,
    required this.rolePersonnelList,
    required this.nodeType,
    required this.ticketReceiptId,
    super.key,
  });

  final Function(List<RolePersonnelEntity> entity) callback; //点击回调
  final List<RolePersonnelEntity> rolePersonnelList; //初始的数据
  final String nodeType; //节点类型
  final String ticketReceiptId; //作业票id

  @override
  State<CustomResponsiblePerson> createState() => _CustomResponsiblePersonState();
}

class _CustomResponsiblePersonState extends State<CustomResponsiblePerson> {
  // 流程逻辑
  String nodeResponsibleType = ''; // 节点负责人类型
  List<RolePersonnelEntity> nodeSelectResponsibleList = []; // 选择的节点负责人

  // 业务逻辑
  List<String> workNameList = []; // 作业中人员类型
  Map<String, List<RolePersonnelEntity>> rolePersonnelMap = {}; //根据人员类型对应选择的人员

  @override
  void initState() {
    super.initState();
    // 初始化数据
    _initData();
  }

  void _initData() {
    //设置初始值
    workNameList.clear();
    rolePersonnelMap.clear();
    nodeSelectResponsibleList = widget.rolePersonnelList;
    //获取负责人类型
    switch (widget.nodeType) {
      //作业申请
      case SpecialJobCode.jobApplication:
        // nodeResponsibleType = '申请人';
        break;
      //气体分析
      case SpecialJobCode.gasAnalysis:
        // nodeResponsibleType = '气体分析人';
        break;
      //安全措施
      case SpecialJobCode.safetyMeasures:
        // nodeResponsibleType = '监护人';
        break;
      //安全交底
      case SpecialJobCode.safetyDisclosure:
        workNameList.add('安全交底人');
        rolePersonnelMap['安全交底人'] = [];

        workNameList.add('接受交底人');
        rolePersonnelMap['接受交底人'] = [];
        // nodeResponsibleType = '安全交底人';
        break;
      //作业审批
      case SpecialJobCode.jobApproval:
        // nodeResponsibleType = '监护人';
        break;
      //作业关闭
      case SpecialJobCode.jobClose:
        nodeResponsibleType = '验收人';
        workNameList.add('验收人');
        rolePersonnelMap['验收人'] = [];
        break;
      //其他自定义节点
      default:
        // nodeResponsibleType = '执行人';
        break;
    }
  }

  /// 获取人员姓名显示
  String _getResponsibleNameView(String workType) {
    final List<RolePersonnelEntity>? personList = rolePersonnelMap[workType];
    if (personList == null || personList.isEmpty) {
      return '请选择$workType';
    }
    return personList.map((e) => e.getShowName()).join(',');
  }

  /// 上传人员作业列表
  Future<void> uploadOperatorList() async {
    // 选择的人员
    final List<ExecuteTicketReceiptListOperatorLists> operatorList = [];

    for (var workName in rolePersonnelMap.keys) {
      // 类型下选择的人员
      final List<RolePersonnelEntity> personList = rolePersonnelMap[workName] ?? [];
      for (var item in personList) {
        final ExecuteTicketReceiptListOperatorLists bean = ExecuteTicketReceiptListOperatorLists();
        bean.operatorUserId = item.userId;
        bean.operatorUserName = item.getShowName();
        bean.operatorType = PersonnelType.getOperatorType(name: workName);
        bean.ticketReceiptId = widget.ticketReceiptId;
        operatorList.add(bean);
      }
    }
    final res = await HttpUtil()
        .generatePostRequest(
          Interface.uploadOperatorList,
          data: operatorList.toString(),
        )
        .execute();
    res.onSuccess((result) {
      widget.callback(rolePersonnelMap[nodeResponsibleType] ?? []);
      Navigator.pop(context);
      AppToast.showSuccess('选择成功');
    });
    res.onError((result) {
      AppToast.showError('选择失败');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      child: Container(
        width: 300.w,
        height: 210.w,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(20.w)),
          gradient: const LinearGradient(
              //渐变位置
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              //渐变颜色[始点颜色, 结束颜色]
              colors: [
                Color(0xffE7EAFF),
                Color(0xffffffff),
                Color(0xffffffff),
                Color(0xffffffff),
              ]),
        ),
        child: Stack(
          alignment: Alignment.center,
          children: [
            Container(
                padding: EdgeInsets.symmetric(horizontal: 30.w, vertical: 12.w),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Text(
                      '人员选择',
                      style: TextStyle(color: Colors.black, fontSize: 18.sp, fontWeight: FontWeight.bold),
                    ),
                    Expanded(
                      child: Center(
                          child: SingleChildScrollView(
                        child: Column(
                            children: workNameList.asMap().keys.map<Widget>((index) {
                          // 人员类型
                          final String workType = workNameList[index];
                          // 类型下选择的人员
                          final List<RolePersonnelEntity> personList = rolePersonnelMap[workType] ?? [];
                          return Container(
                              height: 32.w,
                              padding: EdgeInsets.symmetric(horizontal: 12.w),
                              margin: EdgeInsets.only(bottom: 10.w),
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  border:
                                      Border.all(color: const Color(0xff262F38).withOpacity(0.5), width: 1.w),
                                  borderRadius: BorderRadius.all(Radius.circular(8.w))),
                              child: Row(
                                children: [
                                  Expanded(
                                      child: Text(
                                    _getResponsibleNameView(workType),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    style: TextStyle(
                                        fontSize: 14.sp,
                                        fontWeight: FontWeight.w400,
                                        color: personList.isEmpty
                                            ? const Color(0xffA0A7B5)
                                            : const Color(0xff262F38)),
                                  )),
                                  Icon(Icons.arrow_forward_ios,
                                      size: 14.sp, color: const Color(0xff262F38).withOpacity(0.5))
                                ],
                              )).clickOnce(() {
                            Get.toNamed(AppRoutes.personnelSelection, arguments: {
                              'queryParameters': {'roleName': workType},
                              'isRadio': false,
                            })?.then((value) {
                              //如果不为空则设置人员信息
                              if (value != null) {
                                final List<RolePersonnelEntity> personList =
                                    value as List<RolePersonnelEntity>;
                                rolePersonnelMap[workType] = personList;
                                setState(() {});
                              }
                            });
                          });
                        }).toList()),
                      )),
                    ),
                    SizedBox(
                      width: 270.w,
                      height: 40.w,
                      child: ElevatedButton(
                        style: ButtonStyle(
                          backgroundColor: MaterialStateProperty.all(const Color(0xff5C6DFF)),
                        ),
                        child: Text(
                          '确定',
                          style: TextStyle(fontSize: 16.sp, color: Colors.white),
                        ),
                        onPressed: () {
                          for (var workType in rolePersonnelMap.keys) {
                            // 类型下选择的人员
                            final List<RolePersonnelEntity> personList = rolePersonnelMap[workType] ?? [];
                            if (personList.isEmpty) {
                              AppToast.showError('请选择$workType');
                              return;
                            }
                          }
                          // 调用接口,将人员信息添加到业务中
                          uploadOperatorList();
                        },
                      ),
                    )
                  ],
                )),
            Positioned(
                top: 2.w,
                right: 8.w,
                child: IconButton(
                  icon: Container(
                    width: 30.w,
                    height: 30.w,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(15.w)),
                    ),
                    child: Icon(
                      Icons.close,
                      color: Colors.grey,
                      size: 21.w,
                    ),
                  ),
                  onPressed: () {
                    Navigator.pop(context);
                  },
                ))
          ],
        ),
      ),
    );
  }
}
